package marksys.free.com.marksys.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.arch.lifecycle.LiveData;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import marksys.free.com.marksys.R;
import marksys.free.com.marksys.nettool.MyApi;
import marksys.free.com.marksys.nettool.common.Resource;
import marksys.free.com.marksys.nettool.vo.Detail;
import marksys.free.com.marksys.nettool.vo.Photo;
import marksys.free.com.marksys.ui.adapter.CardPagerAdapter;
import marksys.free.com.marksys.ui.adapter.CardPagerViewAdapter;
import marksys.free.com.marksys.ui.adapter.DepthPageTransformer;
import marksys.free.com.marksys.ui.adapter.PhotoEntity;
import marksys.free.com.marksys.ui.adapter.TestAdapter;
import marksys.free.com.marksys.ui.common.SpaceItemDecoration;
import marksys.free.com.marksys.ui.custom.AutoDismissProgressDialog;
import marksys.free.com.marksys.ui.face.CameraPreviewActivity;
import marksys.free.com.marksys.utils.FileUtils;
import marksys.free.com.marksys.utils.ImageUtil;
import marksys.free.com.marksys.utils.ShowErrTool;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import timber.log.Timber;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String KEY = "KEY";
    public static final String DETAIL = "DETAIL";

    private ViewPager vp;
    private CardPagerAdapter cardPagerAdapter;
    private CardPagerViewAdapter cardPagerViewAdapter;
    private ArrayList<PhotoEntity> mData = new ArrayList<>(0);
    private boolean isShowType = true;
    private boolean isShowProject = true;
    private boolean isShowContext = true;
    private boolean isShowReason = true;
    private boolean isShowClass = true;
    int typePosition = 0;
    int projectPosition = 0;
    int causePosition = 0;
    int classPosition = 0;
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    public static final int CAMERA_PREVIEW = 3;
    private Uri imageUri;
    long id;
    long classid;
    long reasonid;
    String images;
    boolean openFirst = true;
    ArrayList<Long> grayprojectlist;
    ArrayList<String> typelist;
    ArrayList<String> projectlist;
    ArrayList<Long> idlist;
    ArrayList<Long> reasonlist;
    ArrayList<String> causelist;
    ArrayList<String> classlist;
    ArrayList<Long> classIdlist;
    ArrayList<Double> contextlist;
    ArrayList<Double> scorelist;
    TextView textCategory;
    TextView textProject;
    TextView textClass;
    TextView textContext;
    TextView textCause;
    EditText textCauseDetail;
    ImageView backBtn;
    ImageView image_tapCategory;
    ImageView image_tapProject;
    ImageView image_tapClass;
    ImageView image_tapContext;
    ImageView image_tapCause;
    RecyclerView typeRecyclerView;
    RecyclerView projectRecyclerView;
    RecyclerView contextRecyclerView;
    RecyclerView reasonRecyclerView;
    RecyclerView classRecyclerView;
    Long recordID;
    int z;
    TestAdapter typeAdapter = new TestAdapter(true, true, true);
    TestAdapter projectAdapter = new TestAdapter(true, true, true);
    TestAdapter contextAdapter = new TestAdapter(true, true, true);
    TestAdapter causeAdapter = new TestAdapter(true, true, true);
    TestAdapter classAdapter = new TestAdapter(true, true, true);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        typelist = new ArrayList<>();
        typelist.add("洁");
        typelist.add("律");
        typelist.add("勤");

        vp = this.findViewById(R.id.viewpager);

        cardPagerAdapter = new CardPagerAdapter(this, mData);
        cardPagerAdapter.setDelListener(position -> {
            mData.remove(position);
            cardPagerAdapter.notifyDataSetChanged();
            vp.setBackgroundResource(R.drawable.no_photo);
        });
        cardPagerViewAdapter = new CardPagerViewAdapter(this, mData);
        vp.setPageMargin(30);
        vp.setOffscreenPageLimit(3);
        vp.setPageTransformer(false, new DepthPageTransformer());
        vp.setAdapter(cardPagerAdapter);
        vp.setCurrentItem(cardPagerAdapter.getCount() / 2);
        //todo 滑动到最新添加的照片

        textCategory = findViewById(R.id.textCategory);
        textProject = findViewById(R.id.textProject);
        textClass = findViewById(R.id.textClass);
        textContext = findViewById(R.id.textContext);
        textCause = findViewById(R.id.textCause);
        textCauseDetail = findViewById(R.id.textCauseDetail);
        backBtn = findViewById(R.id.backBtn);
        image_tapCategory = findViewById(R.id.image_tapCategory);
        image_tapProject = findViewById(R.id.image_tapProject);
        image_tapClass = findViewById(R.id.image_tapClass);
        image_tapContext = findViewById(R.id.image_tapContext);
        image_tapCause = findViewById(R.id.image_tapCause);
        classRecyclerView = findViewById(R.id.classRecyclerView);
        typeRecyclerView = findViewById(R.id.typeRecyclerView);
        projectRecyclerView = findViewById(R.id.projectRecyclerView);
        contextRecyclerView = findViewById(R.id.contextRecyclerView);
        reasonRecyclerView = findViewById(R.id.reasonRecyclerView);
        Button mTakePhoto = findViewById(R.id.choose_photo);
        Button mTakeAlbum = findViewById(R.id.choose_album);
        Button mFacePhoto = findViewById(R.id.face_photo);
        //设置recycleview的item上下左右边距
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(SpaceItemDecoration.TOP_DECORATION, 10);//top间距
        stringIntegerHashMap.put(SpaceItemDecoration.BOTTOM_DECORATION, 10);//bottom间距
        stringIntegerHashMap.put(SpaceItemDecoration.LEFT_DECORATION, 0);//左间距
        stringIntegerHashMap.put(SpaceItemDecoration.RIGHT_DECORATION, 0);//右间距0
        classRecyclerView.addItemDecoration(new SpaceItemDecoration(stringIntegerHashMap));
        typeRecyclerView.addItemDecoration(new SpaceItemDecoration(stringIntegerHashMap));
        projectRecyclerView.addItemDecoration(new SpaceItemDecoration(stringIntegerHashMap));
        contextRecyclerView.addItemDecoration(new SpaceItemDecoration(stringIntegerHashMap));
        reasonRecyclerView.addItemDecoration(new SpaceItemDecoration(stringIntegerHashMap));

        typeRecyclerView.setAdapter(typeAdapter);
        contextRecyclerView.setAdapter(contextAdapter);

        findViewById(R.id.tapClass).setOnClickListener(this);
        findViewById(R.id.tapCategory).setOnClickListener(this);
        findViewById(R.id.tapProject).setOnClickListener(this);
        findViewById(R.id.tapClass).setOnClickListener(this);
        findViewById(R.id.tapContext).setOnClickListener(this);
        findViewById(R.id.tapCause).setOnClickListener(this);

        int key = getIntent().getIntExtra(KEY, 0);
        if (key == 2) {
            mFacePhoto.setVisibility(View.GONE);
            mTakeAlbum.setVisibility(View.GONE);
            mTakePhoto.setVisibility(View.GONE);
            Detail detail = getIntent().getParcelableExtra(DETAIL);
            recordID = detail.id;
            classid = detail.classId;
            images = detail.image;
            id = detail.project;
            reasonid = detail.reasonId;
            switch (detail.type) {
                case 1:
                    textCategory.setText("洁");
                    break;
                case 2:
                    textCategory.setText("律");
                    break;
                case 3:
                    textCategory.setText("雅");
                    break;
                case 4:
                    textCategory.setText("勤");
                    break;
            }
            image_tapCategory.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            textProject.setText(detail.projectName);
            image_tapProject.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            //获得评分项目
            showProject(detail.type);
            showClassDialog();
            textClass.setText(detail.className);
            image_tapClass.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            textContext.setText(String.valueOf(detail.score));
            image_tapContext.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            if (!TextUtils.isEmpty(detail.reason)) {
                textCause.setText(detail.reason);
                image_tapCause.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                MyApi.cause(detail.project).observe(SettingActivity.this, causeResource -> {
                    assert causeResource != null;
                    assert causeResource.data != null;
                    switch (causeResource.status) {
                        case LOADING:
                            AutoDismissProgressDialog.get(this).show("加载中...");
                            break;
                        case SUCCESS:
                            AutoDismissProgressDialog.get(this).dismiss();
                            reasonRecyclerView.setAdapter(causeAdapter);
                            Log.i(TAG, "data=" + causeResource.data);
                            causelist = new ArrayList<>();
                            reasonlist = new ArrayList<>();
                            scorelist = new ArrayList<>();
                            int size = causeResource.data.size();
                            for (int i = 0; i < size; i++) {
                                causelist.add(causeResource.data.get(i).reasons);
                                reasonlist.add(causeResource.data.get(i).id);
                                scorelist.add(causeResource.data.get(i).score);
                            }
                            Timber.i("scorelist= %s", scorelist);
                            showCauseDialog();
                            break;
                        case ERROR:
                            AutoDismissProgressDialog.get(this).dismiss();
                            ShowErrTool.show(causeResource.errorCode, SettingActivity.this, causeResource.errorMessage);
                            break;
                        default:
                            break;
                    }
                });

            } else {
                reasonRecyclerView.setVisibility(View.GONE);
                isShowReason = false;
            }
            textCauseDetail.setText(detail.content);
            if (images != null) {
                String[] split = images.split(",");
                displayImage(Arrays.asList(split));
            }
        }
        showClassDialog();
        showTypeDialog();

        backBtn.setOnClickListener(v -> this.finish());
        mTakePhoto.setOnClickListener((View view) -> {
            if (key == 2) {
                initDialog();
            } else {
                if (mData.size() < 6) {
                    openCamera();
                } else {
                    simpleDialog("照片最多只能上传6张");
                }
            }
        });
        mTakeAlbum.setOnClickListener((View view) -> {
            if (key == 2) {
                initDialog();
            } else {
                Timber.i("mData %s", mData.size());
                if (mData.size() < 6) {
                    openAlbum();
                } else {
                    simpleDialog("照片最多只能上传6张");
                }
            }
        });
        mFacePhoto.setOnClickListener((View view) -> openCameraForFace());
        findViewById(R.id.confirmBtn).setOnClickListener(view -> {
            if (key == 1) {
                push();
            } else if (key == 2) {
                modify();
            }
        });
    }

    private void openCameraForFace() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //相机请求权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //说明没有开权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 101);
            } else {
                startActivityForResult(new Intent(this, CameraPreviewActivity.class), CAMERA_PREVIEW);
            }
        } else {
            startActivityForResult(new Intent(this, CameraPreviewActivity.class), CAMERA_PREVIEW);
        }
    }

    LiveData<Resource<List<Photo>>> uploadFiles(List<PhotoEntity> photoEntities) {
        List<MultipartBody.Part> parts = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
            Log.e(TAG, "parts: " + mData.get(i).path);
            File file = new File(photoEntities.get(i).path);

            if (file.length() > 0) {
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                parts.add(part);
            }
        }
        return MyApi.upload(parts);
    }

    protected void simpleDialog(String msg) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg)
                .setNegativeButton("确认", null)
                .show();
    }

    void push() {
        if (!checkContent()) {
            return;
        }
        if (mData == null || mData.size() == 0) {
            releaseRecord(null);
        } else {
            LiveData<Resource<List<Photo>>> resourceLiveData = uploadFiles(mData);
            resourceLiveData.observe(this, listResource -> {
                assert listResource != null;
                switch (listResource.status) {
                    case LOADING:
                        AutoDismissProgressDialog.get(this).show("正在上传 ... ");
                        break;
                    case SUCCESS:
                        AutoDismissProgressDialog.get(this).dismiss();
                        releaseRecord(listResource.data);
                        break;
                    case ERROR:
                        AutoDismissProgressDialog.get(this).dismiss();
                        ShowErrTool.show(listResource.errorCode, SettingActivity.this, listResource.errorMessage);
                        break;
                    default:
                        break;
                }
            });
        }
    }

    void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    void releaseRecord(List<Photo> imagesList) {
        String detail = textCauseDetail.getText().toString();
        double score = Double.parseDouble(textContext.getText().toString());
        StringBuilder images = new StringBuilder();
        if (imagesList != null && imagesList.size() > 0) {
            for (int i = 0; i < imagesList.size(); i++) {
                images.append(imagesList.get(i).id).append(",");
            }
        }
        String imagesStr = "";
        if (!TextUtils.isEmpty(images)) {
            imagesStr = images.substring(0, images.length() - 1);
        }
        if (TextUtils.isEmpty(textCause.getText().toString())) {
            reasonid = 0;
        }
        Timber.i("detail %s", detail);
        MyApi.push(id, classid, reasonid, score, imagesStr, null, detail).observe(this, apiResultResource -> {
            assert null != apiResultResource;
            switch (apiResultResource.status) {
                case LOADING:
                    AutoDismissProgressDialog.get(this).show("正在上传 ... ");
                    break;
                case SUCCESS:
                    AutoDismissProgressDialog.get(this).dismiss();
                    Toast.makeText(SettingActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    finish();
                    Intent intent = new Intent(this, SettingActivity.class);
                    intent.putExtra(SettingActivity.KEY, 1);
                    startActivity(intent);
                    break;
                case ERROR:
                    toast("Error ,code = " + apiResultResource.errorCode);
                    AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(apiResultResource.errorCode, SettingActivity.this, apiResultResource.errorMessage);
                    break;
                default:
                    break;
            }
        });
    }

    void modify() {
        if (!checkContent()) {
            return;
        }
        String detail = textCauseDetail.getText().toString();
        double score = Double.parseDouble(textContext.getText().toString());
        if (TextUtils.isEmpty(textCause.getText().toString())) {
            reasonid = 0;
        }
        MyApi.modify(recordID, id, classid, reasonid, score, images, null, detail).observe(this, apiResultResource -> {
            assert null != apiResultResource;
            switch (apiResultResource.status) {
                case LOADING:
                    AutoDismissProgressDialog.get(this).show("正在上传 ... ");
                    break;
                case SUCCESS:
                    AutoDismissProgressDialog.get(this).dismiss();
                    Toast.makeText(SettingActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();
                    break;
                case ERROR:
                    AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(apiResultResource.errorCode, SettingActivity.this, apiResultResource.errorMessage);
                    break;
                default:
                    break;
            }
        });
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            assert im != null;
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            textCauseDetail.clearFocus();
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tapCategory: {
                if (isShowType) {
                    isShowType = false;
                    typeRecyclerView.setVisibility(View.GONE);
                } else {
                    showTypeDialog();
                    isShowType = true;
                }
            }
            break;
            case R.id.tapProject: {
                if (isShowProject) {
                    projectRecyclerView.setVisibility(View.GONE);
                    isShowProject = false;
                } else {
                    isShowProject = true;
                    openFirst = false;
                    showProjectDialog();
                }
            }
            break;
            case R.id.tapClass: {
                if (isShowClass) {
                    classRecyclerView.setVisibility(View.GONE);
                    isShowClass = false;
                } else {
                    isShowClass = true;
                    showClassDialog();
                }
            }
            break;
            case R.id.tapContext: {
                if (isShowContext) {
                    contextRecyclerView.setVisibility(View.GONE);
                    isShowContext = false;
                } else {
                    isShowContext = true;
                    showContextDialog();
                }
            }
            break;
            case R.id.tapCause: {
                if (isShowReason) {
                    reasonRecyclerView.setVisibility(View.GONE);
                    isShowReason = false;
                } else {
                    isShowReason = true;
                    showCauseDialog();
                }
            }
            break;
        }
    }

    private void showTypeDialog() {
        typeAdapter.replace(typelist);
        typeRecyclerView.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(textCategory.getText().toString())) {
            textCategory.setText(typelist.get(0));
            image_tapCategory.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            int type = 1;
            //获得评分项目
            showProject(type);
        } else {
            int type = 0;
            for (int n = 0; n < typelist.size(); n++) {
                if (typeAdapter.getItem(n).equals(textCategory.getText().toString())) {
                    typeAdapter.setDefault(n);
                    type = n + 1;
                    if (n == 2) {
                        type = n + 2;
                    }
                }
            }
            project(type);
        }

        typeAdapter.setOnCheckChangeListener((String text, boolean checked) -> {
            textCategory.setText(text);
            for (int i = 0; i < typelist.size(); i++) {
                if (text.equals(typelist.get(i))) {
                    typePosition = i;
                }
            }
            textProject.setText("");
            projectlist = null;
            idlist = null;
            textCause.setText("");
            causelist = null;
            textContext.setText("");
            contextlist = null;
            scorelist = null;

            String category = textCategory.getText().toString();
            if (!TextUtils.isEmpty(category)) {
                image_tapCategory.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            }
            int type = typePosition + 1;
            if (typePosition == 2) {
                type = typePosition + 2;
            }
            showProject(type);
        });
    }

    private void showProjectDialog() {
        Timber.i("projectlist %s", projectlist);
        if (projectlist != null && projectlist.size() > 0) {
            if (!TextUtils.isEmpty(textClass.getText().toString())) {
                MyApi.today(classid).observe(this, apiResultResource -> {
                    assert null != apiResultResource;
                    switch (apiResultResource.status) {
                        case LOADING:
                            break;
                        case SUCCESS:
                            assert apiResultResource.data != null;
                            Timber.i("pro %s", apiResultResource.data.pro);
                            grayprojectlist = new ArrayList<>();
                            grayprojectlist = apiResultResource.data.pro;
                            for (int i = 0; i < grayprojectlist.size(); i++) {
                                for (int n = 0; n < idlist.size(); n++) {
                                    if (idlist.get(n).equals(grayprojectlist.get(i))) {
                                        //textView.setTextColor
                                        projectAdapter.setGrayDefault(n, this);
                                    }
                                }
                            }
                            break;
                        case ERROR:
                            ShowErrTool.show(apiResultResource.errorCode, SettingActivity.this, apiResultResource.errorMessage);
                            break;
                        default:
                            break;
                    }
                });
            }
            projectAdapter.replace(projectlist);
            projectRecyclerView.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(textProject.getText().toString())) {
                textProject.setText(projectlist.get(0));
                image_tapProject.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                id = idlist.get(0);
                MyApi.cause(id).observe(SettingActivity.this, causeResource -> {
                    assert causeResource != null;
                    assert causeResource.data != null;
                    switch (causeResource.status) {
                        case LOADING:
                            //showRequestPictureDialog progress bar加载框
                            //Snackbar.make(view, "Loading", Snackbar.LENGTH_SHORT).showRequestPictureDialog();
                            AutoDismissProgressDialog.get(this).show("加载中...");
                            break;
                        case SUCCESS:
                            AutoDismissProgressDialog.get(this).dismiss();
                            reasonRecyclerView.setAdapter(causeAdapter);
                            Log.i(TAG, "data=" + causeResource.data);
                            causelist = new ArrayList<>();
                            reasonlist = new ArrayList<>();
                            scorelist = new ArrayList<>();
                            int size = causeResource.data.size();
                            for (int i = 0; i < size; i++) {
                                causelist.add(causeResource.data.get(i).reasons);
                                reasonlist.add(causeResource.data.get(i).id);
                                scorelist.add(causeResource.data.get(i).score);
                            }
                            Timber.i("scoreList= %s", scorelist);
                            showCauseDialog();
                            break;
                        case ERROR:
                            AutoDismissProgressDialog.get(this).dismiss();
                            ShowErrTool.show(causeResource.errorCode, SettingActivity.this, causeResource.errorMessage);
                            break;
                        default:
                            break;
                    }
                });
            } else {
                for (int n = 0; n < projectlist.size(); n++) {
                    if (projectAdapter.getItem(n).equals(textProject.getText().toString())) {
                        projectAdapter.setDefault(n);
                        id = idlist.get(n);
                    }
                }
                cause(id);
            }
            projectAdapter.setOnCheckChangeListener((String text, boolean checked) -> {
                textProject.setText(text);
                for (int i = 0; i < projectlist.size(); i++) {
                    if (text.equals(projectlist.get(i))) {
                        projectPosition = i;
                    }
                }
                textCause.setText("");
                causelist = null;
                reasonlist = null;
                textContext.setText("");
                contextlist = null;
                scorelist = null;

                String project = textProject.getText().toString();
                if (!TextUtils.isEmpty(project)) {
                    image_tapProject.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                }
                id = idlist.get(projectPosition);
                Timber.i("id= %s", id);
                cause(id);
            });
        } else {
            projectRecyclerView.setVisibility(View.GONE);
        }
    }

    private void showContextDialog() {
        if (contextlist != null && contextlist.size() > 0) {
            ArrayList<String> scoreTolist = new ArrayList<>();
            String scoreTo;
            for (int i = 0; i < 6; i++) {
                if (i == 0) {
                    scoreTolist.add("0");
                } else {
                    scoreTo = String.valueOf(contextlist.get(i - 1));
                    scoreTolist.add(scoreTo);
                }
            }
            Timber.i("scoreTolist= %s", scoreTolist);
            contextAdapter.replace(scoreTolist);
            contextRecyclerView.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(textContext.getText().toString())) {
                textContext.setText(scoreTolist.get(0));
            } else {
                for (int n = 0; n < scoreTolist.size(); n++) {
                    if (contextAdapter.getItem(n).equals(textContext.getText().toString())) {
                        contextAdapter.setDefault(n);
                    }
                }
            }
            contextAdapter.setOnCheckChangeListener((text, checked) -> textContext.setText(text));
            String context = textContext.getText().toString();
            if (!TextUtils.isEmpty(context)) {
                image_tapContext.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            }
        } else {
            contextRecyclerView.setVisibility(View.GONE);
        }
    }

    private void showCauseDialog() {
        if (causelist != null && causelist.size() > 0) {
            causeAdapter.replace(causelist);
            reasonRecyclerView.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(textCause.getText().toString())) {
                textCause.setText(causelist.get(0));
                image_tapCause.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                Timber.i("reasonlist %s", reasonlist);
                reasonid = reasonlist.get(0);
                z = 0;
            } else {
                for (int n = 0; n < causelist.size(); n++) {
                    if (causeAdapter.getItem(n).equals(textCause.getText().toString())) {
                        causeAdapter.setDefault(n);
                        z = n;
                    }
                }
            }

            causeAdapter.setOnCheckChangeListener((String text, boolean checked) -> {
                textCause.setText(text);
                for (int i = 0; i < causelist.size(); i++) {
                    if (text.equals(causelist.get(i))) {
                        causePosition = i;
                    }
                }
                /*textContext.setText("");
                contextlist = null;
                scorelist = null;*/

                String cause = textCause.getText().toString();
                if (!TextUtils.isEmpty(cause)) {
                    image_tapCause.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                }

                reasonid = reasonlist.get(causePosition);
                z = causePosition;
            });
            Double score = scorelist.get(z);
            Double scoreNum = 0.0;
            contextlist = new ArrayList<>();
            for (int n = 0; n < 5; n++) {
                scoreNum += -1.0 * score;
                contextlist.add(scoreNum);
            }
            showContextDialog();
        } else {
            reasonRecyclerView.setVisibility(View.GONE);
        }
    }

    private void showClassDialog() {
        MyApi.grades().observe(SettingActivity.this, classResource -> {
            assert classResource != null;
            assert classResource.data != null;
            switch (classResource.status) {
                case LOADING:
                    AutoDismissProgressDialog.get(this).show("加载中...");
                    break;
                case SUCCESS:
                    AutoDismissProgressDialog.get(this).dismiss();
                    Log.i(TAG, "data=" + classResource.data);
                    classRecyclerView.setAdapter(classAdapter);
                    classlist = new ArrayList<>();
                    classIdlist = new ArrayList<>();
                    int size = classResource.data.size();
                    for (int i = 0; i < size; i++) {
                        for (int n = 0; n < classResource.data.get(i).getClasses().size(); n++) {
                            classlist.add(classResource.data.get(i).grade + "(" + classResource.data.get(i).getClasses().get(n).getNum() + ")班");
                            classIdlist.add(classResource.data.get(i).getClasses().get(n).getId());
                        }
                    }
                    classAdapter.replace(classlist);
                    classRecyclerView.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(textClass.getText().toString())) {
                        textClass.setText(classlist.get(0));
                        classid = classIdlist.get(0);
                        image_tapClass.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
                    } else {
                        for (int n = 0; n < classlist.size(); n++) {
                            if (classAdapter.getItem(n).equals(textClass.getText().toString())) {
                                classAdapter.setDefault(n);
                            }
                        }
                    }
                    break;
                case ERROR:
                    AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(classResource.errorCode, SettingActivity.this, classResource.errorMessage);
                    break;
                default:
                    break;
            }
        });

        classAdapter.setOnCheckChangeListener((String text, boolean checked) -> {
            textClass.setText(text);
            for (int i = 0; i < classlist.size(); i++) {
                if (text.equals(classlist.get(i))) {
                    classPosition = i;
                    classid = classIdlist.get(classPosition);
                }
            }
            String classText = textClass.getText().toString();
            if (!TextUtils.isEmpty(classText)) {
                image_tapClass.setImageDrawable(getResources().getDrawable(R.mipmap.selected));
            }
        });
    }

    //打开相机
    private void openCamera() {
        //创建file对象，用于存储拍照后的图片；
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/images/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

        } catch (Exception e) {
            e.printStackTrace();
        }

        imageUri = Uri.fromFile(file);
        //启动相机程序
        //Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
        //启动拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "you denied the permission album ", Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    Toast.makeText(this, "you denied the permission camera", Toast.LENGTH_SHORT).show();
                }
                break;
            case 101:
                // If request is cancelled, the result arrays are empty.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功进入二维码扫秒界面
                    startActivityForResult(new Intent(this, CameraPreviewActivity.class), CAMERA_PREVIEW);
                } else {
                    Toast.makeText(this, "摄像头权限没有打开", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        File outFile1 = ImageUtil.compressImage(imageUri.getPath(), 640, 480);//这里采用的Compressor图片压缩
                        mData.add(new PhotoEntity(outFile1.getAbsolutePath(), true));
                        cardPagerAdapter.notifyDataSetChanged();
                        /*mData.add(new PhotoEntity(imageUri.getPath(), true));
                        cardPagerAdapter.notifyDataSetChanged();*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    String path;
                    if (Build.VERSION.SDK_INT >= 19) {  //4.4及以上的系统使用这个方法处理图片；
                        path = handleImageOnKitKat(data);
                    } else {
                        path = handleImageBeforeKitKat(data);  //4.4及以下的系统使用这个方法处理图片
                    }
                    if (TextUtils.isEmpty(path) || new File(path).length() == 0) {
                        Toast.makeText(SettingActivity.this, "照片不存在！", Toast.LENGTH_SHORT).show();
                    } else {
                        new Thread() {
                            @Override
                            public void run() {
                                File outFile = ImageUtil.compressImage(path, 640, 480);//这里采用的Compressor图片压缩
                                runOnUiThread(() -> displayImage(outFile.getAbsolutePath()));
                            }
                        }.start();
                    }
                }
                break;
            case CAMERA_PREVIEW:
                if (resultCode == RESULT_OK) {
                    String className = data.getStringExtra("className");
                    String stuName = data.getStringExtra("stuName");
                    classid = data.getLongExtra("classId", 0);
                    //Toast.makeText(this, stuName + className, Toast.LENGTH_SHORT).show();
                    textCauseDetail.setText(className + stuName);
                    for (int i = 0; i < classIdlist.size(); i++) {
                        if (classIdlist.get(i).equals(classid)) {
                            classAdapter.setDefault(i);
                            textClass.setText(classlist.get(i));
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    private String handleImageBeforeKitKat(Intent data) {
        Uri imageUri = data.getData();
        assert imageUri != null;
        return FileUtils.getFilePathByUri(this, imageUri);
    }

    private void displayImage(List<String> imagePath) {
        vp.setAdapter(cardPagerViewAdapter);
        Log.e(TAG, "displayImage: " + imagePath);
        if (imagePath != null && imagePath.size() > 0) {
            vp.setBackgroundResource(R.color.background);
            for (int i = 0; i < imagePath.size(); i++) {
                mData.add(new PhotoEntity(imagePath.get(i), true));
            }
            Log.e(TAG, "mData: " + mData);
            cardPagerViewAdapter.notifyDataSetChanged();
        }
    }

    private void displayImage(String imagePath) {
        Log.e(TAG, "displayImage: " + imagePath);
        if (imagePath != null) {
            vp.setBackgroundResource(R.color.background);
            mData.add(new PhotoEntity(imagePath, true));
            Log.e(TAG, "mData: " + mData);
            cardPagerAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }


    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private static final String TAG = "SettingActivity";

    @TargetApi(19)
    private String handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果document类型的Uri,则通过document来处理
            String docID = DocumentsContract.getDocumentId(uri);
            assert uri != null;
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docID.split(":")[1];     //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID));
                imagePath = getImagePath(contentUri, null);
            }

        } else {
            assert uri != null;
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                //如果是content类型的uri，则使用普通方式使用
                imagePath = getImagePath(uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                //如果是file类型的uri，直接获取路径即可
                imagePath = uri.getPath();
            }
        }
        return imagePath;
    }

    private boolean checkContent() {
        String grades = textClass.getText().toString();
        String category = textCategory.getText().toString();
        String project = textProject.getText().toString();
        String context = textContext.getText().toString();
        String cause = textCause.getText().toString();
        if (TextUtils.isEmpty(grades)) {
            Toast.makeText(SettingActivity.this, "请选择评分班级", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(category)) {
            Toast.makeText(SettingActivity.this, "请选择评分类别", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(project)) {
            Toast.makeText(SettingActivity.this, "请选择评分项目", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(cause)) {
            Toast.makeText(SettingActivity.this, "请选择评分原因", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(context)) {
            Toast.makeText(SettingActivity.this, "请选择评分情况", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void initDialog() {
        new AlertDialog.Builder(SettingActivity.this)
                .setTitle("确认")
                .setMessage("已上传的评分记录不能修改照片！")
                .setPositiveButton("确定", null)
                .show();
    }

    void cause(long id) {
        MyApi.cause(id).observe(SettingActivity.this, causeResource -> {
            assert causeResource != null;
            assert causeResource.data != null;
            switch (causeResource.status) {
                case LOADING:
                    AutoDismissProgressDialog.get(this).show("加载中...");
                    break;
                case SUCCESS:
                    AutoDismissProgressDialog.get(this).dismiss();
                    reasonRecyclerView.setAdapter(causeAdapter);
                    Log.i(TAG, "data=" + causeResource.data);
                    causelist = new ArrayList<>();
                    reasonlist = new ArrayList<>();
                    scorelist = new ArrayList<>();
                    int size = causeResource.data.size();
                    for (int i = 0; i < size; i++) {
                        causelist.add(causeResource.data.get(i).reasons);
                        reasonlist.add(causeResource.data.get(i).id);
                        scorelist.add(causeResource.data.get(i).score);
                    }
                    showCauseDialog();
                    break;
                case ERROR:
                    AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(causeResource.errorCode, SettingActivity.this, causeResource.errorMessage);
                    break;
                default:
                    break;
            }
        });
    }

    void showProject(int type) {
        MyApi.projects(type).observe(SettingActivity.this, listResource -> {
            assert listResource != null;
            assert listResource.data != null;
            switch (listResource.status) {
                case LOADING:
                    //showRequestPictureDialog progress bar加载框
                    //Snackbar.make(view, "Loading", Snackbar.LENGTH_SHORT).showRequestPictureDialog();
                    //AutoDismissProgressDialog.get(this).show("加载中...");
                    break;
                case SUCCESS:
                    //AutoDismissProgressDialog.get(this).dismiss();
                    projectRecyclerView.setAdapter(projectAdapter);
                    Log.i(TAG, "data=" + listResource.data);
                    projectlist = new ArrayList<>();
                    idlist = new ArrayList<>();
                    int size = listResource.data.size();
                    Log.i(TAG, "size=" + listResource.data.size());
                    for (int i = 0; i < size; i++) {
                        projectlist.add(listResource.data.get(i).name);
                        idlist.add(listResource.data.get(i).id);
                    }
                    showProjectDialog();
                    break;
                case ERROR:
                    //AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(listResource.errorCode, SettingActivity.this, listResource.errorMessage);
                    break;
                default:
                    break;
            }
        });
    }

    void project(int type) {
        MyApi.projects(type).observe(SettingActivity.this, listResource -> {
            assert listResource != null;
            assert listResource.data != null;
            switch (listResource.status) {
                case LOADING:
                    AutoDismissProgressDialog.get(this).show("加载中...");
                    break;
                case SUCCESS:
                    AutoDismissProgressDialog.get(this).dismiss();
                    projectRecyclerView.setAdapter(projectAdapter);
                    Log.i(TAG, "data=" + listResource.data);
                    projectlist = new ArrayList<>();
                    idlist = new ArrayList<>();
                    int size = listResource.data.size();
                    Log.i(TAG, "size=" + listResource.data.size());
                    for (int i = 0; i < size; i++) {
                        projectlist.add(listResource.data.get(i).name);
                        idlist.add(listResource.data.get(i).id);
                    }
                    break;
                case ERROR:
                    AutoDismissProgressDialog.get(this).dismiss();
                    ShowErrTool.show(listResource.errorCode, SettingActivity.this, listResource.errorMessage);
                    break;
                default:
                    break;
            }
        });
    }
}